'''
Created on 2011-04-04

@author: jasisz
'''
import sys
from PyQt4 import QtGui, QtCore
from propertiesDialog import Ui_ResourceDialog
from fieldDialog import Ui_FieldDialog
from resizeDialog import Ui_ResizeDialog
from gameObjects import Resource, Field, Rule, Action
from ruleDialog import Ui_RuleDialog
from actionDialog import Ui_ActionDialog
import yaml

class ActionDialog(QtGui.QDialog):
    def __init__(self, fieldsList, namesList):
        QtGui.QDialog.__init__(self)        
        self.ui = Ui_ActionDialog()
        self.ui.setupUi(self)
        self.ui.fromBox.addItems(fieldsList)
        self.ui.toBox.addItems(fieldsList)
        self.ui.whatBox.addItems(namesList)
        
    def getAction(self):
        action = Action()
        action.fieldFrom = str(self.ui.fromBox.currentText())
        return action

class RuleDialog(QtGui.QDialog):
    def __init__(self, parent):
        QtGui.QDialog.__init__(self)
        
        self.ui = Ui_RuleDialog()
        self.ui.setupUi(self)
        self.rule = Rule()
        self.parent = parent
        
    @QtCore.pyqtSlot()
    def on_addGoal_clicked(self):
        namesList = self.parent.getListOfResourcesNames()
        namesList.extend(self.parent.getListOfResourcesTypes())
        showActionDialog(self.parent.getListOfFieldsNames(), namesList)
        
    def getRule(self):
        self.rule.name = (str(self.ui.name.text()))
        return self.rule
    

class ResourceDialog(QtGui.QDialog):
    def __init__(self):
        QtGui.QDialog.__init__(self)
        
        self.ui = Ui_ResourceDialog()
        self.ui.setupUi(self)
        
    #very special decorator - without it slot function would be called twice
    #works only with PyQt > 4.5
    @QtCore.pyqtSlot()
    def on_addProperty_clicked(self):
        item = QtGui.QTableWidgetItem("name here")
        item2 = QtGui.QTableWidgetItem("value here")
        row = self.ui.propertiesTable.rowCount()
        self.ui.propertiesTable.setRowCount(row + 1)
        self.ui.propertiesTable.setItem(row, 0, item)
        self.ui.propertiesTable.setItem(row, 1, item2)
        
    @QtCore.pyqtSlot()
    def on_remove_clicked(self):
        rows = []
        for index in self.ui.propertiesTable.selectedIndexes():
            rows.append(index.row())

        rows.sort()
        rows.reverse()
        prev = -1
        for i in rows:
            if i != prev:
                self.ui.propertiesTable.removeRow(i)
                prev = i
            
    def getResource(self):
        res = Resource(str(self.ui.name.text()))
        if self.ui.type.text():
            res.setType(str(self.ui.type.text()))
        table = self.ui.propertiesTable
        try:
            res.image = self.image
        except AttributeError:
            pass
        for i in range(table.rowCount()):
            #all this messing with tries is to try convert str to int or double first
            name = str(table.item(i, 0).text())
            try:
                value = int(table.item(i, 1).text())
                res.setProperty(name, value)
            except ValueError:
                try:
                    value = float(table.item(i, 1).text())
                    res.setProperty(name, value)
                except ValueError:
                    res.setProperty(name, str(table.item(i, 1).text()))
        print(yaml.dump(res, default_flow_style=False))
        return res
    
    @QtCore.pyqtSlot()
    def on_loadImage_clicked(self):
        #TODO: dodac kopiowanie pliku do directory gry... ??
        fileName = QtGui.QFileDialog.getOpenFileName(self,"Open Image", "/home/jasisz/", "Image Files (*.png *.jpg *.bmp)")
        self.image = str(fileName)

        
class ResizeDialog(QtGui.QDialog):
    def __init__(self, x, y):
        QtGui.QDialog.__init__(self)
        
        self.ui = Ui_ResizeDialog()
        self.ui.setupUi(self)
        self.ui.sliderX.setValue(x)
        self.ui.sliderY.setValue(y)
                
    def getXY(self):
        return (self.ui.sliderX.value(), self.ui.sliderY.value())
    
class FieldDialog(QtGui.QDialog):
    def __init__(self, parent = None, x = 0, y = 0, field = Field()):
        QtGui.QDialog.__init__(self)
        
        self.ui = Ui_FieldDialog()
        self.ui.setupUi(self)
        self.parent = parent
        self.ui.spinBoxX.setMaximum(x)
        self.ui.spinBoxY.setMaximum(y)        
        self.field = field
        
        self.ui.name.setText(field.name)
        try:
            self.ui.capacity.setValue(field.capacity)
        except AttributeError:
            pass
        for i in field.resources:
            item = QtGui.QTableWidgetItem(i.name)
            row = self.ui.resourcesTable.rowCount()
            self.ui.resourcesTable.setRowCount(row + 1)
            self.ui.resourcesTable.setItem(row, 0, item)
        try:
            if field.x:
                self.ui.spinBoxX.setValue(field.x)
                self.ui.spinBoxY.setValue(field.y)
        except AttributeError:
            pass
        try:
            if field.type:
                self.ui.stackBox.setChecked(1)
        except AttributeError:
            pass
        
    @QtCore.pyqtSlot()
    def on_remove_clicked(self):
        rows = []
        for index in self.ui.resourcesTable.selectedIndexes():
            rows.append(index.row())

        rows.sort()
        rows.reverse()
        prev = -1
        for i in rows:
            if i != prev:
                self.field.removeResourceByName(str(
                                                    self.ui.resourcesTable.item(i, 0).text()))
                self.ui.resourcesTable.removeRow(i)
                prev = i
    
    @QtCore.pyqtSlot()
    def on_add_clicked(self):
        res = showResourceDialog()
        self.field.addResource(res)
        item = QtGui.QTableWidgetItem(res.name)
        row = self.ui.resourcesTable.rowCount()
        self.ui.resourcesTable.setRowCount(row + 1)
        self.ui.resourcesTable.setItem(row, 0, item)
                
    def getField(self):
        self.field.name = str(self.ui.name.text())
        self.field.x = int(self.ui.spinBoxX.value())
        self.field.y = int(self.ui.spinBoxY.value())       
        if self.ui.stackBox.isChecked():
            self.field.type = "stack"
        if self.ui.capacity.value():
            self.field.capacity = self.ui.capacity.value()
        print(yaml.dump(self.field, default_flow_style=False))
        return self.field
        
def showResourceDialog():
    """returns new Resource made in dialog"""
    dialog = ResourceDialog()
    if (dialog.exec_()):
        return dialog.getResource()
    return None

def showFieldDialog(parent, size, field):
    """returns new Field made in dialog"""
    print(field)
    dialog = FieldDialog(parent, size.width(), size.height(), field)
    if (dialog.exec_()):
        return dialog.getField()
    return None

def showResizeDialog(size):
    """returns tuple (x,y) size"""
    dialog = ResizeDialog(size.width(),size.height())
    if (dialog.exec_()):
        return dialog.getXY()
    return None

def showRuleDialog(parent):
    """returns new Rule made in dialog"""
    dialog = RuleDialog(parent)
    if (dialog.exec_()):
        return dialog.getRule()
    return None

def showActionDialog(fieldsList, namesList):
    """return new Action made in dialog"""
    dialog = ActionDialog(fieldsList, namesList)
    if (dialog.exec_()):
        return dialog.getAction()
    return None

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    print(showResourceDialog())
    app.exec_()
